package cn.waka.sys.admin.dao;

import cn.waka.sys.admin.object.WechatConfig;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Component
public class WechatConfigDao extends BaseDao {

	public WechatConfig find() {
		String sql = "select app_id,name,app_secret,token,aes_key from s_wechat_config limit 0,1";

		List<WechatConfig> list = this.query(sql, new RowMapper<WechatConfig>() {
			@Override
			public WechatConfig mapRow(ResultSet rs, int rowNum) throws SQLException {
				WechatConfig c = new WechatConfig();
				c.setAppId(rs.getString(1));
				c.setName(rs.getString(2));
				c.setAppSecret(rs.getString(3));
				c.setToken(rs.getString(4));
				c.setAesKey(rs.getString(5));
				return c;

			}
		});
		if (list.size() > 0) {
			WechatConfig config = list.get(0);
			return config;
		}
		return null;
	}

	public WechatConfig findByAppId(String appId) {
		String sql = "select name,app_secret,token,aes_key from s_wechat_config where app_id=? limit 0,1";

		List<WechatConfig> list = this.query(sql, new RowMapper<WechatConfig>() {
			@Override
			public WechatConfig mapRow(ResultSet rs, int rowNum) throws SQLException {

				WechatConfig c = new WechatConfig();
				c.setName(rs.getString(1));
				c.setAppSecret(rs.getString(2));
				c.setToken(rs.getString(3));
				c.setAesKey(rs.getString(4));
				return c;
			}
		}, appId);
		if (list.size() > 0) {
			WechatConfig config = list.get(0);
			config.setAppId(appId);
			return config;
		}
		return null;
	}

	public boolean insertConfig(String appid,String name,String appsecret,String token,String aesKey) {
		String sql="insert s_wechat_config (app_id,name,app_secret,token,aes_key)values(?,?,?,?,?)";
		int r=this.update(sql, appid,name,appsecret,token,aesKey);
		return r>0;
	}
	
	public boolean updateConfig(String oldappid,String appid,String name,String appsecret,String token,String aesKey) {
		String sql="update s_wechat_config set app_id=?,name=?,app_secret=?,token=?,aes_key=? where app_id=?";
		int r=this.update(sql, appid,name,appsecret,token,aesKey,oldappid);
		return r>0;
	}
}
